package com.stylefeng.guns.modular.capitalBudget.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.capitalBudget.service.ICapitalBudgetService;
import com.stylefeng.guns.modular.system.model.CapitalBudget;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 资金预算控制器
 *
 * @author fengshuonan
 * @Date 2018-07-16 15:09:15
 */
@Controller
@RequestMapping("/capitalBudget")
public class CapitalBudgetController extends BaseController {

    private String PREFIX = "/capitalBudget/capitalBudget/";

    @Autowired
    private ICapitalBudgetService capitalBudgetService;

    /**
     * 跳转到资金预算首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "capitalBudget.html";
    }

    /**
     * 跳转到添加资金预算
     */
    @RequestMapping("/capitalBudget_add")
    public String capitalBudgetAdd() {
        return PREFIX + "capitalBudget_add.html";
    }


    /**
     * 跳转到上传资金预算
     */
    @RequestMapping("/capitalBudget_upload")
    public String capitalBudgetUpload() {
        return PREFIX + "capitalBudget_upload.html";
    }


    /**
     * 跳转到修改资金预算
     */
    @RequestMapping("/capitalBudget_update/{capitalBudgetId}")
    public String capitalBudgetUpdate(@PathVariable Integer capitalBudgetId, Model model) {
        CapitalBudget capitalBudget = capitalBudgetService.selectById(capitalBudgetId);
        model.addAttribute("item",capitalBudget);
        LogObjectHolder.me().set(capitalBudget);
        return PREFIX + "capitalBudget_edit.html";
    }

    /**
     * 获取资金预算列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@Platform String platform, String revDate) throws Exception{
        EntityWrapper<CapitalBudget> wrapper = new EntityWrapper<CapitalBudget>();
        if (StringUtils.isBlank(revDate)) {
            wrapper.eq("rev_date", new SimpleDateFormat("yyyy-MM").format(new Date()));
        }else {
            wrapper.eq("rev_date",revDate);
        }
            wrapper.eq("platform",platform);



        return capitalBudgetService.selectList(wrapper);
    }

    /**
     * 新增资金预算
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(CapitalBudget capitalBudget) {
        capitalBudgetService.insert(capitalBudget);
        return SUCCESS_TIP;
    }

    /**
     * 删除资金预算
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer capitalBudgetId) {
        capitalBudgetService.deleteById(capitalBudgetId);
        return SUCCESS_TIP;
    }

    /**
     * 修改资金预算
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(CapitalBudget capitalBudget) {
        capitalBudgetService.updateById(capitalBudget);
        return SUCCESS_TIP;
    }

    /**
     * 资金预算详情
     */
    @RequestMapping(value = "/detail/{capitalBudgetId}")
    @ResponseBody
    public Object detail(@PathVariable("capitalBudgetId") Integer capitalBudgetId) {
        return capitalBudgetService.selectById(capitalBudgetId);
    }




    /**
     * 导入资金预算表
     * @author laoyu
     * @date 2018-07-24
     */
    @PostMapping( "/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request)throws GunsException,Exception{
        capitalBudgetService.adds(file);
        return SUCCESS_TIP;


    }


    /**
     * 下载
     * @param modelMap
     * @param request
     * @param response
     */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response, String revDate)  {



        //查询要导出工资
        if (StringUtils.isBlank(revDate)){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请选择要导出的资金预算表时间");
        }

        String platform = ShiroKit.getUser().getDeptcode();
        String platformName=ShiroKit.getUser().getDeptName();

        EntityWrapper<CapitalBudget> wrapper  = new EntityWrapper<>();
        wrapper.eq("platform",platform);
        wrapper.eq("rev_date",revDate);

        List<CapitalBudget> capitalBudgetList = capitalBudgetService.selectList(wrapper);

        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/capitalBudget.xlsx");

        modelMap.put(TemplateExcelConstants.FILE_NAME, platformName+revDate+"资金预算表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, capitalBudgetService.load(capitalBudgetList,revDate,platform, platformName));
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }

    /**
     * 下载
     * @param modelMap
     * @param request
     * @param response
     */
    @RequestMapping("/download")
    public void download(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response)  {

        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/capitalBudgetModel.xlsx");

        modelMap.put(TemplateExcelConstants.FILE_NAME, ShiroKit.getUser().getDeptcode().toUpperCase()+"xxxx-xx资金预算表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, capitalBudgetService.download());
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }

    /**
     * 资金预算统计收支和余缺
     * @param platform
     * @param revDate
     * @return
     */
    @RequestMapping("/tatol")
    @ResponseBody
    public JSONObject tatol(@Platform String platform,String revDate){
        EntityWrapper<CapitalBudget> wrapper = new EntityWrapper<CapitalBudget>();
        if (StringUtils.isBlank(revDate)) {
            wrapper.eq("rev_date", new SimpleDateFormat("yyyy-MM").format(new Date()));
        }else {
            wrapper.eq("rev_date",revDate);
        }
            wrapper.eq("platform",platform);

        List<CapitalBudget> list = capitalBudgetService.selectList(wrapper);
        JSONObject map = new JSONObject();
        //计统计
        Double incometatol = 0.0;//收入总和
        Double outcometatol = 0.0;//支出总和
        for (CapitalBudget capitalBudget:list){
            if (capitalBudget.getNumber()==null){
                continue;
            }
            if (capitalBudget.getNumber()==1){
                incometatol+=capitalBudget.getIncomeRMB();
            }
            if (capitalBudget.getNumber()==2||capitalBudget.getNumber()==3){
                outcometatol+=capitalBudget.getExpenditureRMB();
            }
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#,###");
        map.put("incometatol",df.format(Math.round(incometatol)));
        map.put("outcometatol",df.format(Math.round(outcometatol)));
        map.put("tatol",df.format(Math.round(incometatol-outcometatol)));//本期余缺
        return map;
    }

}
